
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _BIT_REVERSE_H
#define _BIT_REVERSE_H

#include <stdint.h>

static inline uint8_t BitReverse8(uint8_t x)
{
	uint8_t rev = x;
	
	rev = (rev >> 4) | (rev << 4);	
	rev = ((rev & (uint8_t)0xCCU) >> 2) | ((rev & (uint8_t)0x33U) << 2);	
	rev = ((rev & (uint8_t)0xAAU) >> 1) | ((rev & (uint8_t)0x55U) << 1);	
	
	return rev;
}

static inline uint16_t BitReverse16(uint16_t x)
{
	uint16_t rev = x;
	
	rev = (rev >> 8) | (rev << 8);
	rev = ((rev & (uint16_t)0xF0F0U) >> 4) | ((rev & (uint16_t)0x0F0FU) << 4);
	rev = ((rev & (uint16_t)0xCCCCU) >> 2) | ((rev & (uint16_t)0x3333U) << 2);
	rev = ((rev & (uint16_t)0xAAAAU) >> 1) | ((rev & (uint16_t)0x5555U) << 1);
	
	return rev;
}

static inline uint32_t BitReverse32(uint32_t x)
{
	uint32_t rev = x;
	
	rev = (rev >> 16) | (rev << 16);	
	rev = ((rev & (uint32_t)0xFF00FF00UL) >> 8) | ((rev & (uint32_t)0x00FF00FFUL) << 8);
	rev = ((rev & (uint32_t)0xF0F0F0F0UL) >> 4) | ((rev & (uint32_t)0x0F0F0F0FUL) << 4);
	rev = ((rev & (uint32_t)0xCCCCCCCCUL) >> 2) | ((rev & (uint32_t)0x33333333UL) << 2);
	rev = ((rev & (uint32_t)0xAAAAAAAAUL) >> 1) | ((rev & (uint32_t)0x55555555UL) << 1);
	
	return rev;
}


#endif /* _BIT_REVERSE_H */

